'use strict';

define(['controllers', '../service/analysisService', '../service/schemaService'], function (controllers) {
    controllers.collection.register('AnalysisController', ['$scope', '$routeParams', 'AnalysisService', 'SchemaService', function ($scope, $routeParams, analysisService, schemaService) {
        $scope.collectionId = $routeParams.id;
        $scope.init = function () {
            $scope.analysis_query = true;
            $scope.analysis_index = true;
            $scope.analysis_value = '';

            $scope.analysising = false;

            schemaService.query($scope.collectionId, function(schema) {
                $scope.fields = schema.fields;
                $scope.types = schema.types;
                $scope.typeMap = {};
                for (var i = 0; i < $scope.types.length; i++) {
                    $scope.typeMap[$scope.types[i].name] = $scope.types[i];
                }
                $scope.fieldMap = {};
                for (var i = 0; i < $scope.fields.length; i++) {
                    $scope.fieldMap[$scope.fields[i].name] = $scope.fields[i];
                }
                $scope.analysis_name = schema.uniqueKey;

                $scope.$watch('analysis_name', function () {
                    if ($scope.typeMap[$scope.analysis_name] != null) {
                        $scope.analysis_type = 'type';
                    } else {
                        $scope.analysis_type = 'field';
                    }
                });
            });
        };

        var getByPath  = function (result, paths) {
            var val = result;
            for (var i = 0; i < paths.length; i++) {
                val = val[paths[i]];
                if (val == null) {
                    break;
                }
            }
            return val;
        };

        $scope.analysis = function () {
            if (!$scope.analysis_query && !$scope.analysis_index) {
                return;
            }
            $scope.analysising = true;
            analysisService.analysis($scope.collectionId, {
                name: $scope.analysis_name,
                value: $scope.analysis_value,
                type: $scope.analysis_type,
                query: $scope.analysis_query,
                index: $scope.analysis_index
            }, function (result) {
                $scope.query_field_result = getByPath(result, ['field_names', $scope.analysis_name, 'query', 1]);
                $scope.query_type_result = getByPath(result, ['field_types', $scope.analysis_name, 'query', 1]);
                $scope.index_field_result = getByPath(result, ['field_names', $scope.analysis_name, 'index', 1]);
                $scope.index_type_result = getByPath(result, ['field_types', $scope.analysis_name, 'index', 1]);
            });
        };

        $scope.setAnalysisResult = function (analysis_result) {
            $scope.analysis_result = analysis_result;
        };

        $scope.init();
    }]);
});